﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Telerik.Web.UI;
using TelerikStore.EbayService;

namespace TelerikStore.MasterPages
{
    public partial class Home : System.Web.UI.MasterPage
    {
        private ShoppingCart _shoppingCart;
        public ShoppingCart CurrentCart
        {
            get
            {
                if (_shoppingCart == null)
                {
                    if (Session["ShoppingCart"] != null)
                        _shoppingCart = new ShoppingCart((List<ProductItem>)Session["ShoppingCart"]);
                    else _shoppingCart = new ShoppingCart();
                }

                return _shoppingCart;
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            UpdateShoppingCart();
        }

        protected void RemoveItemFromCartButton_Click(object sender, EventArgs e)
        {
            RadRotatorItem cRotatorItem = (RadRotatorItem)((RadButton)sender).Parent;
            ProductItem cProductItem = CurrentCart.Items[cRotatorItem.Index];

            CurrentCart.RemoveWithQuantity(cProductItem, cProductItem.Quantity);

            RebindCartGrid();
        }

        protected void BuyCartButton_Click(object sender, EventArgs e) 
        {
            CurrentCart.Empty();
            UpdateShoppingCart();
            Response.Redirect("./About.aspx");
        }

        protected void EmptyCartButton_Click(object sender, EventArgs e)
        {
            CurrentCart.Empty();
        }

        protected void CartItemQuantity_TextChanged(object sender, EventArgs e)
        {
            RadRotatorItem cRotatorItem = (RadRotatorItem)((RadNumericTextBox)sender).Parent;
            ProductItem cProductItem = CurrentCart.Items[cRotatorItem.Index];

            int newQuantity = (int)((RadNumericTextBox)sender).Value;
            int delta = newQuantity - cProductItem.Quantity;

            if (delta > 0)
                CurrentCart.AddWithQuantity(cProductItem, Math.Abs(delta));
            else
                CurrentCart.RemoveWithQuantity(cProductItem, Math.Abs(delta));

            RebindCartGrid();
        }

        private void PopulateCartInfoFields()
        {
            ItemsTotalLabel.Text = CurrentCart.TotalProductsCount.ToString();
            PriceTotalLabel.Text = CurrentCart.TotalProductsPrice.ToString();
        }

        private void RebindCartGrid()
        {
            Control mainContentPlaceHolder = FullContent.FindControl("MainContent");

            if (mainContentPlaceHolder != null)
            {
                RadGrid shoppingCartGrid = mainContentPlaceHolder.FindControl("ShoppingCartGrid") as RadGrid;

                if (shoppingCartGrid != null)
                    shoppingCartGrid.Rebind();
            }
        }

        public void UpdateShoppingCart()
        {
            Session["ShoppingCart"] = CurrentCart.Items;
            CartRotator.DataSource = CurrentCart.Items;
            CartRotator.DataBind();

            PopulateCartInfoFields();
        }

        public void AddItemToCart(string itemId)
        {
            Item itemToAdd = GetEbayItemById(itemId);
            AddItemToCart(new ProductItem(itemToAdd));
        }

        public void AddItemToCart(ProductItem itemToAdd)
        {
            CurrentCart.Add(itemToAdd);

            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "addtocartnotification", "showCartNotification()", true);
        }

        private Item GetEbayItemById(string itemId) 
        {
            EBayData ebayContext = new EBayData(new Uri("http://ebayodata.cloudapp.net"));
            string singleItemSearchString = String.Format("Items({1}{0}{1})", itemId, EbayQueryStringsHelper.Quote);

            Item itemToAdd = null;
            try 
	        {	        
		        itemToAdd = ebayContext.Execute<Item>(new Uri(singleItemSearchString, UriKind.Relative)).First<Item>();
	        }
	        catch (Exception)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "ebayexception", "alert(\"An error occured during the item request.\")", true);
	        }

            return itemToAdd;
        }
    }
}
